package cn.iocoder.yudao.module.shop.staff.ws;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.websocket.core.listener.WebSocketMessageListener;
import cn.iocoder.yudao.framework.websocket.core.sender.WebSocketMessageSender;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.api.trade.scan.message.ScanOrderPaidMessage;
import cn.iocoder.yudao.module.shop.staff.pojo.po.ShopStaff;
import cn.iocoder.yudao.module.shop.staff.service.ShopStaffService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

/**
 * WebSocket 扫码收款消息
 *
 * @author 山野羡民
 */
@Slf4j
@Component
public class ScanOrderWebSocket implements WebSocketMessageListener<String> {

    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
    @Autowired(required = false) // 由于 yudao.websocket.enable 配置项，可以关闭 WebSocket 的功能，所以这里只能不强制注入
    private WebSocketMessageSender webSocketMessageSender;

    @Resource
    private ShopStaffService shopstaffService;

    public void sendScanOrderPaidMessage(ScanOrderPaidMessage message) {
        ScanOrderDTO order = message.getOrder();
        order.setShop(null); // 不需要传递店铺信息给客户端
        //List<ShopStaff> shopStaffList = shopstaffService.getByShopId(order.getShopId(), ShopStaffRoleEnum.CASHIER.getValue());
        List<ShopStaff> shopStaffList = shopstaffService.getByShopId(order.getShopId(), null);
        if (CollUtil.isEmpty(shopStaffList)) {
            log.debug("[WebSocket][sendScanOrderPaidMessage] 店铺({})扫码收款成功，无任何店员，忽略发送 WebSocket 消息", order.getShopId());
            return;
        }
        shopStaffList = shopStaffList.stream().filter(staff -> staff.getMemberUserId() != null && staff.getMemberUserId() > 0).toList();
        if (CollUtil.isEmpty(shopStaffList)) {
            log.debug("[WebSocket][sendScanOrderPaidMessage] 店铺({})扫码收款成功，无前台用户店员，忽略发送 WebSocket 消息", order.getShopId());
            return;
        }
        for (ShopStaff staffDO : shopStaffList) {
            webSocketMessageSender.sendObject(UserTypeEnum.MEMBER.getValue(), staffDO.getMemberUserId(), "scan-order-paid", order);
            log.debug("[WebSocket][sendScanOrderPaidMessage] 店铺({})扫码收款成功，已向前台用户({})店员({})发送 WebSocket 消息", order.getShopId(), staffDO.getMemberUserId(), staffDO.getContactName());
        }
    }

    @Override
    public String getType() {
        return "scan-order-voice-played";
    }

    @Override
    public void onMessage(WebSocketSession session, String message) {
        log.debug("[WebSocket][onMessage][收到扫码收款语音播报的 WebSocket 消息：payNo({})]", message);
    }

}
